let app = getApp()
Page({
    data: {
        hasNum: null,
        renshu: 0,
        renshulist: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    },
    onShow() {
        console.log('全局存的桌号：', app.globalData.zhuohao)
        let list = wx.getStorageSync('cart') || []
        this.setData({
            list,
            hasNum: app.globalData.zhuohao
        })
        this.getTotal()
    },
    // 计算总价格和总数量
    getTotal() {
        let cartList = this.data.list
        let totalMoney = 0
        let totalNum = 0
        cartList.forEach(item => {
            totalNum += item.num
            totalMoney += item.num * item.price
        })
        this.setData({
            totalNum,
            totalMoney
        })
    },

    // 扫码识别桌号
    saoma() {
        wx.scanCode({
            success: res => {
                console.log(res.result)
                app.globalData.zhuohao = res.result
                this.setData({
                    hasNum: res.result
                })
            }
        })
    },

    // 选择就餐人数
    xuanzhong(e) {
        this.setData({
            renshu: e.currentTarget.dataset.item
        })
    },
    // 获取用户输入的备注信息
    getBeizhu(e) {
        this.setData({
            beizhu: e.detail.value
        })
    },
    // 提交订单
    submit() {
        if (!this.data.hasNum) {
            wx.showToast({
                icon: 'error',
                title: '请识别桌号',
            })
        } else if (!this.data.renshu) {
            wx.showToast({
                icon: 'error',
                title: '选择就餐人数',
            })
        } else {
            console.log('执行了提交订单')
            let user = wx.getStorageSync('user')
            if (!user) {
                wx.showToast({
                    icon: 'error',
                    title: '去个人中心登录',
                })
                setTimeout(() => {
                    wx.switchTab({
                        url: '/pages/me/me',
                    })
                }, 1000)
                return
            }
            // 提交订单
            wx.cloud.database().collection('order')
                .add({
                    data: {
                        name: user.nickName,
                        status: 0,
                        address: this.data.hasNum,
                        beizhu: this.data.beizhu,
                        renshu: this.data.renshu,
                        orderList: this.data.list,
                        totalPrice: this.data.totalMoney,
                        time: app.getCurrentTime()
                    }
                }).then(res => {
                    console.log('提交订单成功', res)
                    // 清空购物车
                    wx.setStorageSync('cart', null)
                    // 跳页
                    wx.switchTab({
                      url: '/pages/me/me',
                    })
                }).catch(res => {
                    console.log('提交订单失败', res)
                })
        }
    }
})